package com.icss.ah.orderFee.action;

import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.base.bean.Json;
import com.icss.ah.base.util.DateUtils;
import com.icss.ah.base.util.Escape;
import com.icss.ah.login.bean.UserInfoBean;

@Controller
public class OrderFeeAction extends BaseAction{

	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");
	
	private static final long serialVersionUID = 12314231L;
	
	DecimalFormat format = new DecimalFormat("0.00");
	
	private String status;
	private String begTime;
	private String endTime;
	
	public String toOrderFeePage(){
		String userCode=getUserCodeFromSession();
		UserInfoBean userInfo=getUserInfo(userCode);
		String shopId=userInfo.getShopId();
		String corpId = userInfo.getCorpId();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("mchCode", icssMchCode);
		map.put("shopId", shopId);
		map.put("corpId", corpId);
//		map.put("checkFlag", "true");
		map.put("status", "5");
		//验证历史提现订单状态
		orderFeeService.checkAgentPayOrders(map);
		
		HashMap actualAmount = orderFeeService.queryActualAmount(map);
		
		//获取用户可提现金额
		HashMap shopMoney = orderFeeService.queryShopMoney(map);
		//店铺余额
		String allBillMoney = shopMoney.get("ALL_BILL_MONEY").toString();
		//获取用户已提现以及处理中金额
		HashMap agentPayMoney = orderFeeService.queryUserAgentMoneyInfo(map);
		//实际可提现金额
		double agentMoney = Double.parseDouble(shopMoney.get("ALL_REAL_MONEY").toString())-
			Double.parseDouble(agentPayMoney.get("OVER_MONEY").toString())-Double.parseDouble(agentPayMoney.get("PAYING_MONEY").toString());
		
		boolean balanceCheck = true;
		if(Double.parseDouble(allBillMoney)!=agentMoney){
			balanceCheck = false;
		}
		getRequest().setAttribute("balanceCheck", balanceCheck);
		
		getRequest().setAttribute("actualAmount", actualAmount);
		getRequest().setAttribute("shopMoney", shopMoney);
		getRequest().setAttribute("agentPayMoney", agentPayMoney);
		getRequest().setAttribute("agentMoney", format.format(Double.valueOf(agentMoney)));
		return "toOrderFeePage";
	}
	
	public void queryFeeList(){
		String userCode=getUserCodeFromSession();
		UserInfoBean userInfo=getUserInfo(userCode);
		String shopId=userInfo.getShopId();
		String corpId = userInfo.getCorpId();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("shopId", shopId);
		map.put("corpId", corpId);
		map.put("status", status);
		map.put("begTime", begTime);
		map.put("endTime", endTime);
		map.put("startIndex",getStartIndexMysql());
		map.put("rowNums",getEndIndexMysql());
		dataGridJson = orderFeeService.queryFeeList(map);
		str2Resp(JSONObject.fromObject(dataGridJson).toString());
	}

	public void exportOrderFeeInfo(){
		try {
			String userCode=getUserCodeFromSession();
			UserInfoBean userInfo=getUserInfo(userCode);
			String shopId=userInfo.getShopId();
			String corpId = userInfo.getCorpId();
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("shopId", shopId);
			map.put("corpId", corpId);
			map.put("status", status);
			map.put("begTime", begTime);
			map.put("endTime", endTime);
			String fname = " 已支付清单";
			if("4".equals(status)) fname = " 已送货清单";
			else if("5".equals(status)) fname = " 已收货清单";
			String allPara = begTime + endTime;
			if("".equals(allPara)){
				endTime = DateUtils.getCurrentDate("yyyy-MM-dd");
				begTime = DateUtils.getBursarMonth(-1);
				fname = begTime+" ~ "+endTime+fname;
				map.put("begTime", begTime);
			}else if(!"".equals(begTime)&& !"".equals(endTime)){
				fname = begTime+" ~ "+endTime+fname;
			}
			List<Map<String, Object>> list = orderFeeService.queryExportOrderFeeInfo(map);
			String[] colNames = {"序号","订单号","买家姓名","时间","订单金额（￥）","退款金额（￥）","交易收费（￥）","入账金额（￥）"};
			String[] colParas = {"ORDER_NO","CON_NAME","CREATE_TIME","ORDER_MONEY","REFUND_MONEY","ALL_FEE_MONEY","ACTUALAMOUNT"};
			int [] widths = {8,30,20,20,19,19,19,19};
			createExcel(this.getResponse(), list, fname, colNames, colParas, widths);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderFeeAction|exportOrderFeeInfo|异常：",e);
		}
	}
	
	
	/**
	 * 进入提现界面
	 * @return
	 */
	public String tixian(){
		request = getRequest();
		try {
			UserInfoBean userInfo=getUserInfo("");
			String shopId=userInfo.getShopId();
			String corpId = userInfo.getCorpId();
			
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("mchCode", icssMchCode);
			map.put("shopId", shopId);
			map.put("corpId", corpId);
//			map.put("checkFlag", "true");
			map.put("status", "5");
			//可提现金额
			HashMap actualAmount = orderFeeService.queryActualAmount(map);
			//记录日志
			infolog.info("OrderFeeAction|tixian|actualAmount:"+actualAmount);
			//可提现手续费
			String agentFee = orderFeeService.getAgentFee(new HashMap());
			//记录日志
			infolog.info("OrderFeeAction|tixian|agentFee:"+agentFee);
			//获取用户已提现以及处理中金额
			HashMap agentPayMoney = orderFeeService.queryUserAgentMoneyInfo(map);
			//记录日志
			infolog.info("OrderFeeAction|tixian|agentPayMoney:"+agentPayMoney);
			//实际可提现金额
			double agentMoney = Double.parseDouble(actualAmount.get("ACTUALAMOUNT").toString())-
				Double.parseDouble(agentPayMoney.get("OVER_MONEY").toString())-Double.parseDouble(agentPayMoney.get("PAYING_MONEY").toString());
			//记录日志
			infolog.info("OrderFeeAction|tixian|agentMoney:"+agentMoney);
			request.setAttribute("agentMoney", agentMoney);
			request.setAttribute("actualAmount", actualAmount);
			request.setAttribute("agentFee", agentFee);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderFeeAction|agentPay|异常：",e);
		}
		return "tixian";
	}
	/**
	 * 提现操作
	 */
	public void agentPay(){
		request = getRequest();
		response = getResponse();
		jsonText = new Json();
		try {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			
			UserInfoBean userInfo=getUserInfo("");
			String shopId=userInfo.getShopId();
			//提现金额
			String money = request.getParameter("money");
			money = money == null || money.equals("") ? "0" : money;
			//银行卡号
			String bankAccount = request.getParameter("bankAccount");
			bankAccount = bankAccount == null ? "" : bankAccount;
			//银行开户名
			String bankAccountName = request.getParameter("bankAccountName");
			bankAccountName = bankAccountName == null ? "" : bankAccountName;
			
			if(shopId==null||shopId.equals("")){
				throw new Exception("session过期，请重新登录");
			}
			
			try{
				if(Float.parseFloat(money)<=0){
					throw new Exception("提现金额不得小于等于0元");
				}
			} catch (Exception e) {
				throw new Exception("提现金额不符");
			}
			//参数
			HashMap map = new HashMap();
			map.put("mchCode", icssMchCode);
			map.put("shopId", shopId);
			map.put("orderMoney", money);
			map.put("bankAccount", bankAccount);
			map.put("bankAccountName", bankAccountName);
			//记录日志
			infolog.info("OrderFeeAction|agentPay|map:"+map);
			//保存提现订单并返回提现订单号
			String agentOrder = orderFeeService.saveUserAgentPayInfo(map);
			//记录日志
			infolog.info("OrderFeeAction|agentPay|agentOrder:"+agentOrder);
			if(agentOrder!=null && !agentOrder.equals("")){
				map.put("sellNo", agentOrder);
				//提现操作
				String result = orderFeeService.agentPay(map);
				//记录日志
				infolog.info("OrderFeeAction|agentPay|result:"+result);
				String[] str = result.split(",");
				if("1".equals(str[0])){
					jsonText.setSuccess(true);
					jsonText.setMsg(str[1]);
				} else {
					jsonText.setSuccess(false);
					jsonText.setMsg(str[1]);
				}
			} else {
				throw new Exception("提现订单生成失败，请稍后再试");
			}
			
		} catch (Exception e) {
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
			errlog.error("OrderFeeAction|agentPay|异常：",e);
		} finally {
			try {
				JSONObject json = JSONObject.fromObject(jsonText);
				response.getWriter().print(json.toString());
			} catch (Exception e) {
				errlog.error("OrderFeeAction|agentPay|print异常：",e);
			}
		}
	}
	
	public String toAgentOrderPage(){
		return "toAgentOrderPage";
	}
	
	private String customerName;
	public void queryAgentOrderList(){
		UserInfoBean userInfo=getUserInfo("");
		String shopId=userInfo.getShopId();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("orderStatus", status);
		map.put("begTime", begTime);
		map.put("endTime", endTime);
		map.put("customerName", customerName);
		map.put("shopId", shopId);
		map.put("startIndex",getStartIndexMysql());
		map.put("rowNums",getEndIndexMysql());
		dataGridJson = orderFeeService.queryAgentOrder(map);
		str2Resp(JSONObject.fromObject(dataGridJson).toString());
	}
	
	public void exportAgentOrderInfo(){
		try {
			customerName = Escape.unescape(Escape.unescape(customerName));
			UserInfoBean userInfo=getUserInfo("");
			String shopId=userInfo.getShopId();
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("orderStatus", status);
			map.put("begTime", begTime);
			map.put("endTime", endTime);
			map.put("customerName", customerName);
			map.put("shopId", shopId);
			String allPara = customerName+status+begTime+endTime;
			String fname = " 提现流水";
			if("".equals(allPara)){
				endTime = DateUtils.getCurrentDate("yyyy-MM-dd");
				begTime = DateUtils.getBursarMonth(-1);
				fname = begTime+" ~ "+endTime+fname;
				map.put("begTime", begTime);
			}
			List<Map<String, Object>> list = orderFeeService.queryExportAgentOrder(map);
			String[] colNames = {"序号","订单号","持卡人姓名","提现卡号","实际到账金额（￥）","提现时间","状态"};
			String[] colParas = {"ORDER_NO","CUSTOMER_NAME","ACCOUNT_NUMBER","REAL_MONEY","CREATE_TIME","ORDER_STATUS_NAME"};
			int [] widths = {8,25,20,20,20,20,12};
			createExcel(this.getResponse(), list, fname, colNames, colParas, widths);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("OrderFeeAction|exportAgentOrderInfo|异常：",e);
		}
	}
	/**
	 * 查询提现结果
	 */
	public void checkAgengOrderResult(){
		request = getRequest();
		response = getResponse();
		jsonText = new Json();
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			//获取登录账号信息
			UserInfoBean userInfo = getUserInfo("");
			//代付订单号
			String orderId  = request.getParameter("orderId");
			orderId = orderId == null ? "" : orderId;
			//查询参数
			HashMap map = new HashMap();
			map.put("shopId", userInfo.getShopId());
			map.put("orderId", orderId);
			//记录日志
			infolog.info("OrderFeeAction|checkAgengOrderResult|map:"+map);
			//代付结果查询
			String result = orderFeeService.checkAgengOrderResult(map);
			//记录日志
			infolog.info("OrderFeeAction|checkAgengOrderResult|result:"+result);
			//返回代付查询结果
			String[] str = result.split(",");
			if(str[0].equals("1")){
				jsonText.setSuccess(true);
			} else {
				jsonText.setSuccess(false);
			}
			jsonText.setMsg(str[1]);
		} catch (Exception e) {
			errlog.error("OrderFeeAction|checkAgengOrderResult|异常：",e);
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
		} finally{
			JSONObject json = JSONObject.fromObject(jsonText);
			try {
				//公告提醒信息
				response.getWriter().print(json.toString());
			} catch (IOException e) {
				errlog.error("OrderFeeAction|checkAgengOrderResult|print异常：",e);
			}
			
		}
	}
	
	public void createExcel(HttpServletResponse response,List<Map<String, Object>> list,String fname,String[] colNames,String[] colParas,int [] widths) throws WriteException,IOException{
		response.reset();//清空输出流
	    
		//下面是对中文文件名的处理
		response.setContentType("text/html;charset=utf-8");
		//请求来源浏览器的信息
		String agent = ServletActionContext.getRequest().getHeader("USER-AGENT");
		if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐
			response.setHeader("Content-Disposition","attachment;filename="+ new String(fname.getBytes("GB2312"),"ISO-8859-1")+".xls");
        }else{
        	fname = java.net.URLEncoder.encode(fname,"UTF-8");
			response.setHeader("Content-Disposition","attachment;filename="+new String(fname.getBytes("UTF-8"),"GBK")+".xls");
        }
		response.setContentType("application/msexcel");//定义输出类型
		OutputStream os = response.getOutputStream();
		
		WritableFont wfTitle= new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
    	WritableCellFormat wcfTitle= new WritableCellFormat(wfTitle);	
    	
    	WritableCellFormat formateTitle=new WritableCellFormat(wcfTitle);
    	formateTitle.setAlignment(jxl.format.Alignment.CENTRE);
    	formateTitle.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
    	formateTitle.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
    	formateTitle.setWrap(true);
    	
    	WritableFont wfc= new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
    	WritableCellFormat wcfFC= new WritableCellFormat(wfc);
    	//属性
    	WritableCellFormat formateHead=new WritableCellFormat(wcfFC);
    	formateHead.setAlignment(jxl.format.Alignment.CENTRE);
    	formateHead.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
    	formateHead.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
    	formateHead.setBackground(Colour.AQUA);
    	formateHead.setWrap(true);
    	
    	WritableCellFormat formateBody = new  WritableCellFormat(); 
    	formateBody.setAlignment(jxl.format.Alignment.LEFT);
    	formateBody.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
    	formateBody.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
    	formateBody.setWrap(true);
    	//创建工作薄
    	WritableWorkbook workbook = Workbook.createWorkbook(os);
    	//创建新的一页
    	WritableSheet sheet = workbook.createSheet(fname,0);
    	
    	for(int i=0;i<widths.length;i++){
    		sheet.setColumnView(i,widths[i]);
    	}
    	
    	sheet.setRowView(0,460);
    	sheet.addCell(new Label(0,0,fname,formateTitle));
    	sheet.mergeCells(0,0,colNames.length-1,0);
    	
    	sheet.setRowView(1,400);
    	int rowIndex = 1;
    	for(int i=0;i<colNames.length;i++){
    		sheet.addCell(new Label(i,rowIndex,colNames[i],formateHead));
    	}
    	for(int i=0;i<list.size();i++){
    		sheet.setRowView(++rowIndex,400);
    		Map<String, Object> obj = list.get(i);
    		sheet.addCell(new Label(0,rowIndex,(i+1)+"",formateBody));
    		for(int j=0;j<colParas.length;j++){
    			Object o = obj.get(colParas[j]);
				sheet.addCell(new Label((j+1),rowIndex,o.toString(),formateBody));
    		}
    	}
    	//把创建的内容写入到输出流中，并关闭输出流
    	workbook.write();
    	workbook.close();
    	os.close();
	}
	
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getBegTime() {
		return begTime;
	}

	public void setBegTime(String begTime) {
		this.begTime = begTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public String getCustomerName() {
		return customerName;
	}

	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}

}
